package com.example.pxxy_news.fragment;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.graphics.AvoidXfermode.Mode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.example.pxxy_news.R;
import com.example.pxxy_news.adapter.MyArticleAdapter;
import com.example.pxxy_news.adapter.NewsAdapter;
import com.example.pxxy_news.application.MyApplication;
import com.example.pxxy_news.entity.News;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class FragmentArticleManager extends Fragment{
	private static final String URL_NEWS = "http://10.102.41.48:8080/news_server/NewsServlet";
	View view;
	ListView mListView;
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				List<News> list = (List<News>) msg.obj;
				Log.d("news", list.size()+"");
				MyArticleAdapter maa = new MyArticleAdapter(list);
				mListView.setAdapter(maa);
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		view = inflater.inflate(R.layout.fragment_article_manager, container, false);
		initView();
		setMyArticleAdapter();
		return view;
	}
	private void setMyArticleAdapter() {
		SharedPreferences sp = MyApplication.getContext().getSharedPreferences("user",MyApplication.getContext().MODE_PRIVATE);
		String username = sp.getString("username", "");
		Log.d("news", "kaishigongzuo");
		Log.d("news", username);
		
		OkHttpClient client = new OkHttpClient();
		RequestBody body = new FormBody.Builder().add("operation", "findNewsByName")
				.add("username", username)
				.build();
		Request request = new Request.Builder()
				.url(URL_NEWS)
				.post(body).build();
		
		client.newCall(request).enqueue(new Callback() {
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				String JsonNews = arg1.body().string();
				Gson gson = new Gson();
				List<News> list = gson.fromJson(JsonNews,
						new TypeToken<List<News>>() {
						}.getType());
				Message msg = Message.obtain();
				msg.what = 1;
				msg.obj = list;
				handler.sendMessage(msg);
			}
			
			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void initView() {
		mListView = (ListView) view.findViewById(R.id.fam_list_article);
	}
}
